import store from '../store/store'

let tools = {
  sys(){
    return {
      timestamp : new Date().getTime(),//时间戳
      appChannel : 'WEB',//平台
      version : '1.1.1',//版本号
      appType : 'BUSINESS'//类型
    }
  },
  getParams(){
    return this.$route.params;
  },
  getQuery(){
    return this.$route.query;
  },
  back(){
    this.router.back();
  },
  tourl(url,query){
    this.router.push({path:url,query:query || {}});
  },
  baseUrl:'',//http://120.78.77.215:8095   /rep
  setSession:function(key,val){
    window.sessionStorage[key] = JSON.stringify(val);
  },
  getSession:function(key){

    try{
      let data = window.sessionStorage[key];
      if(data){
        data = JSON.parse(data);
        return data;
      }
    }catch(e){
      return '';
    }
  },
  clearSession:function(){
    window.sessionStorage.clear();
  },
  emptyObj:function(e){
    var t;
    for (t in e)
        return !1;
    return !0
  },
  toastWarn:function(text){

    try{
      this.vue.prototype.$message({
        message: text,
        showClose: true,
        type: 'warning',
        customClass:'toastBox'
      });
    }catch(e){
      throw new Error('tools.alert异常');
    }
  },
  toastOk:function(text){

    try{
      this.vue.prototype.$message({
        message: text,
        showClose: true,
        type: 'success',
        customClass:'toastBox'
      });
    }catch(e){
      throw new Error('tools.alert异常');
    }
  },
	cloneObj : function (obj) {
	    var str, newobj = obj.constructor === Array ? [] : {};
	    if (typeof obj !== 'object') {
	        return;
	    } else if (JSON) {
	        str = JSON.stringify(obj), //序列化对象
	            newobj = JSON.parse(str); //还原

	    } else {
	        for (var i in obj) {
	            newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
	        }
	    }
	    return newobj;
	},
  	ajax:function(obj){
      var _this = this;

      if(!obj.type){
        obj.type = 'POST';
      }

      if(!obj.headers && obj.type == 'POST' || !obj.headers && obj.type == 'PUT' || !obj.headers && obj.type == 'DELETE'){
        obj.headers = {
          'Accept' : 'application/json',
          'Content-Type' : 'application/json'
        }
      }

      obj.headers = obj.headers || {};

      try{
        let timestamp = new Date().getTime();//时间戳
        let appChannel = 'WEB';//平台
        let version = '1.1.0';//版本号
        let appType = 'BUSINESS';//类型

        obj.headers['timestamp'] = timestamp;
        obj.headers['appChannel'] = appChannel;
        obj.headers['version'] = version;
        obj.headers['appType'] = appType;
      }catch(e){

      }

      try{
        var sessionData = this.getSession('userData');
        if(sessionData && sessionData.token){
          obj.headers.token = sessionData.token;
        }

      }catch(e){

      }

      if(obj.data && obj.needJson == void 0 && obj.type != 'GET'){
        obj.data = JSON.stringify(obj.data)
      }
      return new Promise( (resolve, reject) => {
        obj.url = obj.url.replace(/(^\/\w*_service)/,'/matchA$1');

        let selectUserId = 1;

        obj.url = obj.url.replace('{userId}',selectUserId);

        $.ajax({
          headers : obj.headers,
          type: obj.type,
          timeout : 30000, //超时时间设置，单位毫秒
          url:this.baseUrl+obj.url,
          async: true,
          dataType:obj.dataType || 'json',
          data: obj.data || {},
          success: function(res){

            let code = res.code;

            if(obj.url != '/api/shop/get_later_messages'){
              console.log(obj.url +'-----V-----');
              console.log(res);
            }


            if(code == 200){
              return resolve(res);
            }else if(code >= 300 && code <= 399){
              //登录失效 重新登录
              if(code ==  302){
                //没有shopI
                // _this.toastWarn('您当前没有已入驻商店信息，请先去入驻');
                // throw new Error('没有商店或未入驻');
                return resolve(res);
              }else{
                if(sessionData){
                  tools.router.push({path:'/'});
                  _this.toastWarn(res.msg);
                  throw new Error('登录状态异常');
                }
              }
              
            }else if(code >= 400 && code <= 499){
              //数据格式异常
              _this.toastWarn(res.msg);
              return resolve(res);
              throw new Error('数据格式异常');
            }else if(code >= 500 && code <= 599){
              //服务端异常
              _this.toastWarn(res && res.msg || '服务端异常');
              throw new Error('服务端异常');
            }else if(code >= 600){
              //未知异常
              _this.toastWarn(res.msg);
              return resolve(res);
              throw new Error('未知异常');
            }

          },
          error: function(res){
            _this.toastWarn('服务器超时，请稍后再试');
            return resolve(res);
          },
          complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
            if(status=='timeout'){//超时,status还有success,error等值的情况
              console.log('服务器超时，请稍后再试');
              _this.toastWarn('服务器超时，请稍后再试');
            }

      　　}
        });

      });

    }
};

export default tools;